package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.SCustomer;
import com.example.demo.bean.SEmp;
import com.example.demo.bean.SOrd;
import com.example.demo.common.exception.DataValidException;
import com.example.demo.mapper.SCustomerMapper;
import com.example.demo.mapper.SEmpMapper;
import com.example.demo.mapper.SItemMapper;
import com.example.demo.mapper.SOrdMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class SOrdService {
	@Autowired
	private SOrdMapper soMapper;
	@Autowired
	private SCustomerMapper scMapper;
	@Autowired
	private SEmpMapper seMapper;
	@Autowired
	private SItemMapper sItemMapper;
	//搜索所有订单信息
	public PageInfo<SOrd> findAllByPage(int pageNum, int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		//执行查找行为
		List<SOrd> list=soMapper.selectAll();
		if (list==null) {
			list=new ArrayList<SOrd>(0);
		}
		return new PageInfo<SOrd>(list);//返回查找结果
	}
	
	
	//检索数量
	public List<Map<Object, Object>> countOrd(){
		List<Map<Object, Object>> list=soMapper.countOrd();
		return list;
	}
	
	//按照条件搜索订单信息
	public PageInfo<SOrd> findByName(String name, int pageNum, int pageSize){
		PageHelper.startPage(pageNum,pageSize);
		List<SOrd> list= soMapper.selectByName(name);
		if (list==null) {
			list=new ArrayList<>(0);
			System.out.println("====================================================");
		}
		
		return new PageInfo<SOrd>(list);
	}
	
	//添加或修改订单信息
	public void saveOrUpdate(SOrd so) {
		//判断输入的信息是否存在
		if (so.getCustomerId()==null||so.getSalesRepId()==null) {
			//判断两个外键是否存在
			throw new DataValidException("请填写完整信息");
		}else {
			
			SCustomer sc=scMapper.selectByPrimaryKey(so.getCustomerId());
			SEmp se=seMapper.selectByPrimaryKey(so.getSalesRepId());
			if (sc==null||se==null) {
				throw new DataValidException("外键信息不存在");
			}
		}
		if (so.getId()==null) {
			soMapper.insert(so);
		}else {
			soMapper.updateByPrimaryKey(so);
		}
	}
	//根据id删除订单信息
	public int deleteById(Integer id) {
		//判断id为空
		if (id==null) {
			throw new DataValidException("请输入订单id");
		}
		//按照订单id查找信息，如果找不到就提示删除失败
		SOrd so=soMapper.selectByPrimaryKey(id);
		if (so==null) {
			throw new DataValidException("删除失败");
		}
		if (sItemMapper.selectByOrdId(so.getId())!=null) {
			throw new DataValidException("存在下属的库存信息，请删除物品的库存信息后，在进行删除");
		}
		soMapper.deleteByPrimaryKey(id);
		return 0;
	}
	
	//批量删除
	public int batchDeleteById(int[] id) {
		//判断是否为空
		if (id.length==0||id==null) {
			throw new DataValidException("请选择一批id");
		}
		//查找要删除的订单信息
		for (int i : id) {
			SOrd so=soMapper.selectByPrimaryKey(i);
			if (so==null) {
				throw new DataValidException("删除失败");
			}
		}
		//删除订单信息
		soMapper.batchDelete(id);
		return 0;
	}
}
